<template>
  <div class="app-container">
    <!-- main -->
    <div class="main-container">
      <!-- header -->
      <div class="header-box">
        <!-- 查询条件 -->
        <div class="search-box">
        </div>
        <!-- 操作按钮 -->
        <div class="operate-box">
          <Button icon="md-add" type="primary" @click="showAddModal('add')">
            新增
          </Button>
        </div>
      </div>
      <!-- table -->
      <div class="table-box">
        <Table ref="tableRef" :loading="listLoading" height="600" :columns="tableColumns" :data="proList"
          @on-selection-change="handleChange">
          <template slot-scope="{ row, index }" slot="action">
              <Button type="primary" size="small" style="margin-right: 5px"  @click="showEditModal(row,'edit')">编辑</Button>
              <Button type="error" size="small" @click="handleDelete(row)">删除</Button>
          </template>
        </Table>
      </div>
      <!-- paging -->
      <div class="pagination-box">
        <Page :total="listTotal" :current.sync="listQuery.pageNo" :page-size="listQuery.pageSize" show-sizer
          show-elevator show-total :page-size-opts="[10, 20, 30, 50]" @on-change="changePageNo"
          @on-page-size-change="changePageSize" />
      </div>
    </div>

    <!-- 弹框 -->
    <!-- 编辑和新增 -->
    <Modal v-model="editModal" :title="editForm.series_id ? '编辑套系' : '添加套系'" width="640px">
      <div class="padding-left-40 padding-right-40">
        <Form ref="editFormRef" :model="editForm" :rules="editFormRules" :label-width="80">
          <FormItem label="拍摄类型" prop="type_id" required>
            <Select :disabled="flag === 'edit'" v-model="editForm.type_id" placeholder="拍摄类型" clearable style="width: 100%" @on-change="handleTypeChange">
              <Option :value="item.type_id" v-for="item in typeList" :key="item.type_id">{{item.type_name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="套系名称" prop="series_name" required>
            <!-- <Select :disabled="flag === 'edit'" v-model="editForm.series_id" placeholder="套系名称" clearable style="width: 100%" @on-change="handleSeries">
              <Option :value="item.series_id" v-for="item in seriesList" :key="item.series_id">{{item.series_name}}</Option>
            </Select> -->
            <Input v-model="editForm.series_name" placeholder="套系名称" maxlength="100" style="width: 100%" clearable></Input>
          </FormItem>
          <FormItem label="价格" prop="price">
            <Input v-model="editForm.price" placeholder="输入价格" maxlength="100" style="width: 100%" clearable></Input>
          </FormItem>
          <FormItem label="拍摄张数" prop="number_of_shots">
            <InputNumber v-model="editForm.number_of_shots" :min="0"  placeholder="输入拍摄张数"
              style="width: 100%" />
          </FormItem>
          <FormItem label="服装数量" prop="number_of_costumes">
            <InputNumber v-model="editForm.number_of_costumes" :min="0"  placeholder="输入服装数量"
              style="width: 100%" />
          </FormItem>
          <FormItem label="精修数量" prop="number_of_refined">
            <InputNumber v-model="editForm.number_of_refined" placeholder="输入精修数量" maxlength="2" style="width: 100%" clearable />
          </FormItem>
          <FormItem label="场景数量" prop="number_of_scenes">
            <InputNumber v-model="editForm.number_of_scenes" :min="0" placeholder="输入场景数量" style="width: 100%" />
          </FormItem>
          <FormItem label="造型数量" prop="number_of_appearances">
            <InputNumber v-model="editForm.number_of_appearances" :min="0"  placeholder="输入造型数量"
              style="width: 100%" />
          </FormItem>
          <FormItem label="相册列表">
            <Select v-model="array_album_List" multiple placeholder="相册列表" clearable style="width: 100%" @on-change="handleAlbum">
              <Option :value="item.album_id" v-for="item in albumList" :key="item.album_id">{{item.album_name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="相框列表">
            <Select v-model="array_frameid_List" multiple placeholder="相框列表" clearable style="width: 100%" @on-change="handleAlbum">
              <Option :value="item.frame_id" v-for="item in frameList" :key="item.frame_id">{{item.frame_name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="免费礼物">
            <Select v-model="editForm.free_gift" placeholder="免费礼物" clearable style="width: 100%">
              <Option value="无" key="1">无</Option>
            </Select>
          </FormItem>
        </Form>
      </div>
      <div class="text-align-center" slot="footer">
        <Button type="default" @click="editModal = false">取消</Button>
        <Button type="primary" @click="handleSubmit">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  // 引入LimeUtil
  import LimeUtil from "@lime-util/util";
  import axios from "axios";
  // 引入api
  import {
    getList,
    getDetail,
    addProduct,
    updateProduct,
    deleteSeriesApi,
  } from "@/api/product";
  import {
    getAllType,
    getAllSeriesByTypeIdApi,
    getAllAlbumApi,
    getAllFrameApi,
  } from "@/api/order/index";
  export default {
    data() {
      return {
        // 搜索输入收起和展开
        searchCollapse: true,

        // 列表分页
        proList: [],
        listTotal: 0,
        listLoading: false,
        listQuery: {
          type_id: 1,
          pageNo: 1,
          pageSize: 10,
        },
        albumList: [],
        array_frameid_List: [],
        array_album_List: [],
        frameList: [], // 所有相框
        typeList: [],
        seriesList: [], // 所有套系
        // 表格多选和单选
        selectRows: [],
        selectRow: {},

        // 表格列数据
        tableColumns: [
          {
            key: "index",
            title: "序号",
            width: 90,
            align: "center",
            render: (h, { row, index }) => {
              return h("span", index + 1);
            },
          },
          {
            title: "产品名称",
            key: "series_name",
            width: 380,
          },
          {
            title: "价格",
            key: "price",
            width: 120,
          },
          {
            title: "拍摄张数",
            key: "number_of_shots",
            width: 120,
          },
          {
            title: "服装数量",
            key: "number_of_costumes",
            width: 120,
            sortable: true,
          },
          {
            title: "精修数量",
            key: "number_of_refined",
            width: 120,
            sortable: true,
          },
          {
            title: "场景数量",
            key: "number_of_scenes",
            width: 120,
          },
          {
            title: "造型数量",
            key: "number_of_appearances",
            width: 120,
          },
          {
            title: "相册列表",
            key: "album_List",
            width: 300,
            render: (h, params) => {
              const relatedNames = params.row.album_List.split(',').map(id => {
                const relatedData = this.albumList.find(item => item.album_id === parseInt(id));
                return relatedData ? relatedData.album_name : '无';
              });
              return h('span', relatedNames.join(','));
            }
          },
          {
            title: "相框列表",
            key: "frame_List",
            width: 300,
            render: (h, params) => {
              const relatedNames = params.row.frame_List.split(',').map(id => {
                const relatedData = this.frameList.find(item => item.frame_id === parseInt(id));
                return relatedData ? relatedData.frame_name : '无';
              });
              return h('span', relatedNames.join(','));
            }
          },
          {
            title: "免费礼物",
            key: "free_gift",
            width: 180,
          },
          {
            title: "操作",
            slot: "action",
            fixed: "right",
            width: 200,
          },
        ],

        // 新增和编辑
        editModal: false,
        // 表单
        editForm: {
          type_id: 0,
          series_id: "",
          series_name: "",
          price: "",
          number_of_shots: 0,
          number_of_costumes: 0,
          number_of_refined: 0,
          number_of_scenes: 0,
          number_of_appearances: 0,
          album_List: "",
          frame_List: "",
          free_gift: "",
        },
        flag: '',
        // 表单校验
        editFormRules: {
          type_id: [{
            type: "number",
            required: true,
            trigger: "change",
            message: "请选择套系类型"
          }],
          series_name: [{
            required: true,
            trigger: "blur",
            message: "请输入套系名称"
          }]
        },
      };
    },
    async created() {
      this.queryData();
      this.getTypes()
      this.frameList = this.$store.state.layout.app.frameList;
      this.albumList = this.$store.state.layout.app.albumList;
    },
    methods: {
      /**
       * 查询列表
       */
      async queryData() {
        this.listLoading = true;
        getList(this.listQuery)
        .then((res) => {
          console.log('获取所有产品列表', res);
          setTimeout(() => {
            this.listLoading = false;
          }, 300);
          if (res.rstpCode === '0000') {
            this.proList = res.data;
            // this.listTotal = res.data.total;
          } else {
            this.$Message.error(res.rstpMsg);
          }
        })
        .catch((error) => {
          this.listLoading = false;
        });
      },
      // 得到所有的拍摄类型
      getTypes() {
        getAllType().then(res => {
          console.log('得到所有的拍摄类型', res);
          if (res.rstpCode === '0000') {
            this.typeList = res.data;
          } else {
            this.$Message.error(res.rstpMsg);
          }
        })
      },
      // 选择拍摄类型事件
      handleTypeChange(e) {
        console.log(e);
        this.editForm.type_id = e
        if (this.editForm.type_id) {
          this.editForm.type_name = this.typeList.find(item => item.type_id == e).type_name
          this.getAllSeries()
        }
      },
      handleSeries(e) {
        this.editForm.series_name = e
      },
      // 根据拍摄类型得到所有的系列（套系）
      getAllSeries() {
        getAllSeriesByTypeIdApi({
          type_id: this.editForm.type_id
        }).then(res => {
          console.log('根据拍摄类型得到所有的系列（套系）', res);
          if (res.rstpCode === '0000') {
            this.seriesList = res.data;
          } else {
            this.$Message.error(res.rstpMsg);
          }
        })
      },
      handleAlbum() {

      },
      // 重置查询列表
      handleReset() {
        this.listQuery = {
          pageNo: 1,
          pageSize: 10,
        };
        this.queryData();
      },
      // 分页
      changePageNo(val) {
        this.listQuery.pageNo = val;
        this.queryData();
      },
      changePageSize(val) {
        this.listQuery.pageSize = val;
        this.queryData();
      },

      /**
       * 表格多选
       */
      handleChange(rows) {
        this.selectRows = rows;
      },
      /**
       * 清空表格多选
       */
      handleClearRows() {
        this.$refs.tableRef.selectAll(false);
      },

      /**
       * 新增和编辑
       */
      showAddModal(str) {
        this.flag = str
        this.editModal = true;
        // 需要先设置表单数据为空后，再调用重置表单才会起作用
        this.editForm = {
          type_id: "",
          series_id: "",
          series_name: "",
          price: "",
          number_of_shots: 0,
          number_of_costumes: 0,
          number_of_refined: 0,
          number_of_scenes: 0,
          number_of_appearances: 0,
          album_List: "",
          frame_List: "",
          free_gift: "",
        };
        if (this.$refs.editFormRef) {
          this.$refs.editFormRef.resetFields();
        }
      },
      showEditModal(row,str) {
        this.flag = str
        console.log(row);
        this.array_album_List = []
        this.editModal = true;
        this.editForm = {
          type_id: parseInt(row.type_id),
          series_id: parseInt(row.series_id),
          series_name: row.series_name,
          price: row.price,
          number_of_shots: parseInt(row.number_of_shots),
          number_of_costumes: parseInt(row.number_of_costumes),
          number_of_refined: parseInt(row.number_of_refined),
          number_of_scenes: parseInt(row.number_of_scenes),
          number_of_appearances: parseInt(row.number_of_appearances),
          free_gift: row.free_gift,
        };
        row.album_List.split(',').forEach(item => {
          this.array_album_List.push(parseInt(item))
        })
        row.frame_List.split(',').forEach(item => {
          this.array_frameid_List.push(parseInt(item))
        })
        console.log(this.array_album_List);
        this.getAllSeries()
      },
      handleSubmit() {
        this.$refs.editFormRef.validate((valid) => {
          if (valid) {
            if (this.editForm.series_id) {
              this.handleUpdate();
            } else {
              this.handleAdd();
            }
          }
        });
      },
      // 保存
      handleAdd() {
        this.editForm.album_List = this.array_album_List.join(',')
        this.editForm.frame_List = this.array_frameid_List.join(',')
        const formData = new FormData()
        for (let key in this.editForm) {
          formData.append(key, this.editForm[key])
        }
        addProduct(formData).then((res) => {
          if (res.rstpCode === '0000') {
            this.$Message.success("添加成功");
            this.queryData();
            this.editModal = false;
          } else {
            this.$Message.error(res.rstpMsg);
          }
        });
      },
      // 修改
      handleUpdate() {
        this.editForm.album_List = this.array_album_List.join(',')
        this.editForm.frame_List = this.array_frameid_List.join(',')
        console.log('series_id', this.editForm.series_id);
        const formData = new FormData()
        for (let key in this.editForm) {
          formData.append(key, this.editForm[key])
        }
        updateProduct(formData).then((res) => {
          if (res.rstpCode === '0000') {
            this.$Message.success("修改成功");
            this.queryData();
            this.editModal = false;
          } else {
            this.$Message.error(res.rstpMsg);
          }
        });
      },

      /**
       * 删除
       */
      handleDelete(row) {
        this.$Modal.confirm({
          title: "提示",
          content: "确定删除该条数据吗？",
          closable: true,
          onOk: () => {
            deleteSeriesApi({
              series_id: row.series_id
            }).then((res) => {
              if (res.rstpCode == '0000') {
                this.$Message.success("删除成功");
                this.queryData();
              } else {
                this.$Message.error(res.rstpMsg);
              }
            });
          },
        });
      },
    },
  };
</script>

<style lang="less" scoped></style>
